package com.lss.music.utils;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * Android 权限管理工具类
 * 支持Android 6.0+运行时权限申请
 * 适配Android 11+分区存储权限
 */
@RequiresApi(api = Build.VERSION_CODES.Q)
public class PermissionHelper {

    private static final String TAG = "PermissionHelper";

    // 权限请求码
    private static final int READ_PHONE_STATE_CODE = 101;
    private static final int WRITE_EXTERNAL_STORAGE_CODE = 102;
    private static final int ACCESS_MEDIA_LOCATION_CODE = 103;
    private static final int REQUEST_OPEN_APPLICATION_SETTINGS_CODE = 12345;

    // 所需权限列表
    private final PermissionModel[] mPermissionModels = {
            new PermissionModel("电话", Manifest.permission.READ_PHONE_STATE, 
                    "我们需要读取手机信息的权限来标识您的身份", READ_PHONE_STATE_CODE),
            
            new PermissionModel("存储空间", Manifest.permission.WRITE_EXTERNAL_STORAGE, 
                    "我们需要您允许我们读写你的存储卡，以保存音乐文件", WRITE_EXTERNAL_STORAGE_CODE),
            
            new PermissionModel("媒体位置", Manifest.permission.ACCESS_MEDIA_LOCATION, 
                    "我们需要访问媒体位置信息以正确显示音乐文件", ACCESS_MEDIA_LOCATION_CODE)
    };

    private final Activity mActivity;
    private OnApplyPermissionListener mOnApplyPermissionListener;

    public PermissionHelper(Activity activity) {
        this.mActivity = activity;
    }

    public void setOnApplyPermissionListener(OnApplyPermissionListener listener) {
        this.mOnApplyPermissionListener = listener;
    }

    /**
     * 检查并申请所有需要的权限
     */
    public void applyPermissions() {
        // 获取需要申请的权限列表
        List<String> permissionsToRequest = new ArrayList<>();
        for (PermissionModel model : mPermissionModels) {
            if (ContextCompat.checkSelfPermission(mActivity, model.permission) 
                    != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(model.permission);
            }
        }

        if (permissionsToRequest.isEmpty()) {
            // 所有权限都已授予
            if (mOnApplyPermissionListener != null) {
                mOnApplyPermissionListener.onAfterApplyAllPermission();
            }
        } else {
            // 申请缺失的权限
            String[] permissionsArray = permissionsToRequest.toArray(new String[0]);
            ActivityCompat.requestPermissions(mActivity, permissionsArray, 
                    getRequestCodeForPermissions(permissionsArray));
        }
    }

    /**
     * 处理权限请求结果
     */
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        boolean allGranted = true;
        
        // 检查所有请求的权限是否都被授予
        for (int i = 0; i < permissions.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                allGranted = false;
                
                // 检查用户是否选择了"不再询问"
                if (!ActivityCompat.shouldShowRequestPermissionRationale(mActivity, permissions[i])) {
                    // 用户选择了"不再询问"，需要引导用户到设置页面
                    showPermissionDeniedDialog(permissions[i]);
                    return;
                }
            }
        }

        if (allGranted) {
            // 所有权限都已授予
            if (mOnApplyPermissionListener != null) {
                mOnApplyPermissionListener.onAfterApplyAllPermission();
            }
        } else {
            // 部分权限被拒绝，再次尝试申请
            applyPermissions();
        }
    }

    /**
     * 处理设置页面返回结果
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_OPEN_APPLICATION_SETTINGS_CODE) {
            // 用户从设置页面返回，检查权限状态
            if (isAllRequestedPermissionGranted()) {
                if (mOnApplyPermissionListener != null) {
                    mOnApplyPermissionListener.onAfterApplyAllPermission();
                }
            } else {
                // 用户仍未授予必要权限
                showPermissionDeniedDialog(null);
            }
        }
    }

    /**
     * 检查所有需要的权限是否都已授予
     */
    public boolean isAllRequestedPermissionGranted() {
        for (PermissionModel model : mPermissionModels) {
            if (ContextCompat.checkSelfPermission(mActivity, model.permission) 
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 显示权限被拒绝的对话框
     */
    private void showPermissionDeniedDialog(String permission) {
        String permissionName = findPermissionName(permission);
        String permissionExplain = findPermissionExplain(permission);
        
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity)
                .setTitle("权限申请")
                .setMessage("请在设置中开启" + permissionName + "权限，以正常使用本应用\n\n" + permissionExplain)
                .setPositiveButton("去设置", (dialog, which) -> openApplicationSettings())
                .setNegativeButton("取消", (dialog, which) -> {
                    // 用户拒绝必要权限，退出应用
                    mActivity.finish();
                });
        
        builder.setCancelable(false);
        builder.show();
    }

    /**
     * 打开应用设置页面
     */
    private void openApplicationSettings() {
        try {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", mActivity.getPackageName(), null);
            intent.setData(uri);
            mActivity.startActivityForResult(intent, REQUEST_OPEN_APPLICATION_SETTINGS_CODE);
        } catch (Exception e) {
            Log.e(TAG, "打开设置页面失败", e);
            
            // 备用方案：打开系统设置
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            mActivity.startActivity(intent);
        }
    }

    /**
     * 获取权限请求码
     */
    private int getRequestCodeForPermissions(String[] permissions) {
        if (permissions.length > 0) {
            String permission = permissions[0];
            for (PermissionModel model : mPermissionModels) {
                if (model.permission.equals(permission)) {
                    return model.requestCode;
                }
            }
        }
        return WRITE_EXTERNAL_STORAGE_CODE; // 默认返回存储权限请求码
    }

    /**
     * 查找权限名称
     */
    private String findPermissionName(String permission) {
        for (PermissionModel model : mPermissionModels) {
            if (model.permission.equals(permission)) {
                return model.name;
            }
        }
        return "必要权限";
    }

    /**
     * 查找权限说明
     */
    private String findPermissionExplain(String permission) {
        for (PermissionModel model : mPermissionModels) {
            if (model.permission.equals(permission)) {
                return model.explain;
            }
        }
        return "此权限是应用正常运行所必需的";
    }

    /**
     * 权限模型类
     */
    private static class PermissionModel {
        public final String name;
        public final String permission;
        public final String explain;
        public final int requestCode;

        public PermissionModel(String name, String permission, String explain, int requestCode) {
            this.name = name;
            this.permission = permission;
            this.explain = explain;
            this.requestCode = requestCode;
        }
    }

    /**
     * 权限申请回调接口
     */
    public interface OnApplyPermissionListener {
        /**
         * 所有权限申请完成后的回调
         */
        void onAfterApplyAllPermission();
    }
}